#!/usr/bin/env python
# -*- coding: utf8 -*-
# replace.py

import re, time
from difflib import get_close_matches
from core.ircfuncs import is_channel

"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low",
  default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Required.
* aliases: list of string or regexp objects. Optional.
* fullmsg: boolean. Optional. If True, pattern is searched on whole message, else
  pattern is a command, the message must begin with a sign.

* access
* evttypes
* ignore
* limit
* channels
* url
"""

def substitute_(bot, evt, cmd):
	old=cmd.dict["old"]
	new=cmd.dict["new"]
	if bot.notes.has_key(evt.source) and bot.notes[evt.source].has_key(evt.target):
		for msg in reversed(bot.notes[evt.source][evt.target]):
			if old in msg:
				repeat=cmd.dict['repeat']
				max=msg.count(repeat)
				if not repeat or repeat=="*":
					msg=msg.replace(old, new)
				elif cmd.dict['repeat'].isdigit():
					repeat=int(repeat)
					if repeat>max:repeat=max
					msg=msg.replace(old, new, int(repeat))

				bot.reply(evt, u"$nick meant: %s", msg)
				break
substitute_.rule=re.compile("^s/(?P<old>[^/]+)/(?P<new>[^/]+)/(?P<repeat>(?:\d+|\*)?)$")
substitute_.fullmsg=True
substitute_.limit=2

def mistake_(bot, evt, cmd):
	if bot.notes.has_key(evt.source) and bot.notes[evt.source].has_key(evt.target):
		for msg in reversed(bot.notes[evt.source][evt.target][:-1]):
			result = get_close_matches(cmd.dict['good'].lower(), msg.split(" "), n=10)
			if result:
				msg = msg.replace(result[0], cmd.dict['good'].strip("*"))
				bot.reply(evt, "$nick meant: %s", msg)
				break
mistake_.rule=re.compile("^(?P<good>\*[^ ]+|[^ ]+\*)$")
mistake_.fullmsg=True

#TODO rergister commands in a history file
def memory(bot, evt, cmd):
	if not hasattr(bot, "notes"):
		bot.notes = {}
	report = is_channel(evt.target) and bot.channels.has_key(evt.target) and bot.channels[evt.target].report
	if evt.type == "pubmsg":
		if bot.notes.has_key(evt.source):
			if not evt.msg.startswith("s/") and not evt.msg.startswith(bot.triggers.replace("\\","")) and not evt.msg.startswith(bot.current_nname):
				if bot.notes[evt.source].has_key(evt.target):
					bot.notes[evt.source][evt.target].append(evt.msg)
				else:
					bot.notes[evt.source]={evt.target:[evt.msg]}
			if bot.notes[evt.source].has_key(evt.target):
				if len(bot.notes[evt.source][evt.target]) > 5: bot.notes[evt.source][evt.target]=bot.notes[evt.source][evt.target][1:]
		else:
			bot.notes[evt.source]={evt.target:[evt.msg]}
		if report: bot.ctrl_msg(evt, "{$chan} <$nick> $msg".replace("$msg", evt.msg))
	elif evt.type in ("quit", "disconnect", "part"):
		if not is_channel(evt.target):
			rpt = []
			for chan in bot.channels:
				if evt.target in bot.channels[chan].users():
					rpt.append(bot.channels[chan].report)
			report = eval(" and ".join([str(x) for x in rpt])) if rpt else False
		if report: bot.reply(evt,
			"%s has %s %s",
			evt.source,
			"%sted" % evt.type if evt.type == "quit" else "%sed" % evt.type,
			evt.target if is_channel(evt.target) else bot.features.network()
		)
		if evt.source in bot.notes:
			del bot.notes[evt.source]
	elif hasattr(bot, "sendall") and bot.sendall:
		bot.ctrl_msg(evt, "&B;type&N; %s &B;source&N; %s &B;target&N; %s &B;msg&N; %s" %(evt.type, evt.source, evt.target, evt.msg))
memory.rule=False
memory.evttypes="*"
memory.priority="high"
memory.skip_sentinel=True

def buffer_(bot, evt, cmd):
	import hashlib
	bot.reply(evt, "%i buffers" % (len(bot._buffer)))
	i=0;j=0;x=0;y=0
	for buffer in bot._buffer.copy():
		x+=1
		b = bot._buffer[buffer]
		if b[1].name in ("memory", "note_"):
			del bot._buffer[buffer]
			i+=1
			continue
		elif time.time() - b[0]> 900:
			del bot._buffer[buffer]
			j+=1
			continue
		y += 1
		bot.reply(evt, "%i b: %s %s | f: %s | s: %s | t: %s | c: %s | cmd: %s |  cl: '%s' |h: [%s]" % (
				y,
				buffer,
				time.strftime("%H:%M:%S", time.localtime(b[0])),
				b[1].name,
				b[2].source,
				b[2].target,
				b[2].chan,
				b[3].command,
				b[3].cmdline,
				hashlib.md5("".join([b[1].name or "", b[2].source or "", b[2].chan or "", b[2].target or "", b[3].command, b[3].cmdline])).hexdigest()
			)
		)
	bot.reply(evt, "%i old buffer deleted | %i note/mem buffer deleted | total: %i" % (j, i, i+j))
buffer_.rule = "buffer"
buffer_.thread = True
